﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Threading;
using Dimebrain.TweetSharp;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Model;

namespace AndyPike.Experiments.Twitter
{
    public partial class Window1
    {
        private DispatcherTimer timer;
        private TwitterClientInfo clientInfo;

        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            clientInfo = new TwitterClientInfo { ClientName = "Prickle", ClientUrl = "http://andypike.com", ClientVersion = "0.1" };

            timer = new DispatcherTimer {Interval = 5.Minutes()};
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            Refresh();
        }

        private void Tweet_Click(object sender, RoutedEventArgs e)
        {
            UpdateStatus();
        }
        
        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        private void UpdateStatus()
        {
            ITwitterStatusUpdate twitter = FluentTwitter.CreateRequest(clientInfo)
                .AuthenticateAs(username.Text, password.Password)
                .Statuses()
                .Update(status.Text)
                .AsJson();

            twitter.Request();

            Refresh();

            status.Text = string.Empty;
        }

        private void Refresh()
        {
            ITwitterFriendsTimeline twitter = FluentTwitter.CreateRequest(clientInfo)
                .AuthenticateAs(username.Text, password.Password)
                .Statuses()
                .OnFriendsTimeline() 
                .AsJson();

            string response = twitter.Request();

            IEnumerable<TwitterStatus> statuses = response.AsStatuses();

            timeline.Text = string.Empty;
            foreach (var twitterStatus in statuses)
            {
                timeline.Text += twitterStatus.User.ScreenName + ":\t" + twitterStatus.Text + " (" + twitterStatus.CreatedDate.ToRelativeTime() + ")\r\n";
            }

            message.Content = "Last updated: " + DateTime.Now.ToShortTimeString();
        }
    }
}
